import uuid
from BloodSpiderAPI import models
from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_page
from BloodSpiderAPI.apis.script.topic.utils import script_topic_to_dict


def script_topic_create(request):
    """
    创建话题话术
    请求方式: POST
    参数:
        category_id: 分类ID (必填)
        content: 话术内容 (必填)
        order: 排序值 (必填, 数字越大越靠后)
        status: 话术状态 (必填, 1-正常, 2-禁用)
        description: 描述 (选填, 字符串)
    返回:
        创建的话题话术信息
    """
    try:
        # 获取参数
        category_id = request.POST.get('category_id')
        content = request.POST.get('content')
        order = int(request.POST.get('order', 0))
        status = int(request.POST.get('status', 1))
        description = request.POST.get('description', '')

        # 参数验证
        if not category_id:
            return response_dict(code=1, message="分类ID参数错误, 不能为空")
        if not content:
            return response_dict(code=1, message="话术内容参数错误, 不能为空")
        if status not in [1, 2]:
            return response_dict(code=1, message="话术状态参数错误, 仅支持1(正常)或2(禁用)")

        # 检查分类是否存在
        category = models.ScriptCategory.objects.filter(category_id=category_id).first()
        if not category:
            return response_dict(code=1, message="话术分类不存在")

        # 创建话题话术记录
        new_topic = models.TopicScript.objects.create(
            category_id=category_id,
            content=content,
            order=order,
            status=status,
            description=description
        )

        # 构造返回数据
        return response_dict(data=script_topic_to_dict(new_topic), message="话题话术创建成功")
    except Exception as e:
        return response_dict(code=1, message=f"话题话术创建失败: {str(e)}")


def script_topic_list(request):
    """
    获取话题话术列表
    请求方式: GET
    参数:
        category_id: 分类ID (选填)
        status: 话术状态 (选填, 1-正常, 2-禁用)
        sort_by: 排序字段 (选填, 支持order/-order/create_time/-create_time, 默认:order)
        page: 页码 (选填, 默认:1)
        page_size: 每页数量 (选填, 默认:10)
    返回:
        话题话术列表, 支持分页
    """
    try:
        # 获取参数
        category_id = request.GET.get('category_id')
        status = request.GET.get('status')
        sort_by = request.GET.get('sort_by', 'order')
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))

        # 构建查询条件
        queryset = models.TopicScript.objects.all().select_related('category')  # 使用select_related优化查询
        if category_id:
            queryset = queryset.filter(category_id=category_id)
        if status:
            queryset = queryset.filter(status=int(status))

        # 排序
        allowed_sort_fields = ['order', '-order', 'create_time', '-create_time']
        if sort_by not in allowed_sort_fields:
            sort_by = 'order'
        queryset = queryset.order_by(sort_by)
        # 分页
        page_data = get_page(queryset, page_size, page)

        # 构造返回数据
        result_list = [script_topic_to_dict(item) for item in page_data["page"]['object_list']]
        del page_data["page"]['object_list']

        return response_dict(data=result_list, message="话题话术列表获取成功")
    except Exception as e:
        return response_dict(code=1, message=f"话题话术列表获取失败: {str(e)}")


def script_topic_detail(request):
    """
    获取话题话术详情
    请求方式: GET
    参数:
        topic_id: 话术ID (必填)
    返回:
        话题话术详情信息
    """
    try:
        # 获取参数
        topic_id = request.GET.get('topic_id')

        # 参数验证
        if not topic_id:
            return response_dict(code=1, message="话术ID参数错误, 不能为空")

        # 查询话题话术
        topic = models.TopicScript.objects.filter(topic_id=topic_id).select_related('category').first()
        if not topic:
            return response_dict(code=1, message="话题话术不存在")

        # 构造返回数据
        return response_dict(data=script_topic_to_dict(topic), message="话题话术详情获取成功")
    except Exception as e:
        return response_dict(code=1, message=f"话题话术详情获取失败: {str(e)}")


def script_topic_update(request):
    """
    更新话题话术
    请求方式: POST
    参数:
        topic_id: 话术ID (必填)
        category_id: 分类ID (选填)
        content: 话术内容 (选填)
        order: 排序值 (选填)
        status: 话术状态 (选填)
    返回:
        更新后的话题话术信息
    """
    try:
        # 获取参数
        topic_id = request.POST.get('topic_id')
        content = request.POST.get('content')
        status = int(request.POST.get('status', 1))

        # 参数验证
        if not topic_id:
            return response_dict(code=1, message="话术ID参数错误, 不能为空")

        # 查询话题话术
        topic = models.TopicScript.objects.filter(script_id=topic_id).first()
        if not topic:
            return response_dict(code=1, message="话题话术不存在")

        if content:
            topic.content = content
     
        if status:
            status = int(status)
            if status not in [1, 2]:
                return response_dict(code=1, message="话术状态参数错误, 仅支持1(正常)或2(禁用)")
            topic.status = status
       

        topic.save()

        # 构造返回数据
        return response_dict(data=script_topic_to_dict(topic), message="话题话术更新成功")
    except Exception as e:
        return response_dict(code=1, message=f"话题话术更新失败: {str(e)}")


def script_topic_delete(request):
    """
    删除话题话术
    请求方式: POST
    参数:
        topic_id: 话术ID (必填)
    返回:
        删除结果
    """
    try:
        # 获取参数
        script_id = request.POST.get('script_id')

        # 参数验证
        if not script_id:
            return response_dict(code=1, message="话术ID参数错误, 不能为空")

        # 查询话题话术
        topic = models.TopicScript.objects.filter(script_id=script_id).first()
        if not topic:
            return response_dict(code=1, message="话题话术不存在")

        # 删除话题话术 (物理删除, 可根据需求改为逻辑删除)
        topic.delete()

        return response_dict(message="话题话术删除成功")
    except Exception as e:
        return response_dict(code=1, message=f"话题话术删除失败: {str(e)}")